package com.promote.algorithm;

/**
 * @ClassName SearchInsert
 * Description 搜索插入位置--35
 * @Author LiZiHao
 * Date 2021/10/28 11:25
 * @Version 1.0
 **/
public class SearchInsert {

    public static int searchInsert(int[] nums, int target) {

        int n = nums.length;
        int l = 0;
        int r = n - 1;
        int ans = n;

        while (l <= r) {

            int mid = (r - l) / 2 + l;
            if (nums[mid] >= target) {
                ans = mid;
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] nums = {-1, 0, 3, 5, 9, 12};
        int target = 6;
        int i = searchInsert(nums, target);
        System.out.println(i);
    }

    public int searchInsert1(int[] nums, int target) {
        //二分法
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        return left;
    }
}
